import React, { useState } from 'react';
import styled from 'styled-components';
import { motion, AnimatePresence } from 'framer-motion';
import { colors, spacing, breakpoints } from '../styles/variables';
import { changePassword } from '../services/api';
import { logInfo, logError } from '../logger';

// 弹窗背景
const ModalOverlay = styled(motion.div)`
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  padding: ${spacing.md};
`;

// 弹窗内容
const ModalContent = styled.div`
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  width: 100%;
  max-width: 400px;
  overflow: hidden;
`;

// 弹窗头部
const ModalHeader = styled.div`
  padding: ${spacing.lg};
  border-bottom: 1px solid ${colors.border};
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

// 弹窗标题
const ModalTitle = styled.h2`
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
  color: ${colors.text};
`;

// 关闭按钮
const CloseButton = styled.button`
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: ${colors.textSecondary};
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &:hover {
    color: ${colors.text};
  }
`;

// 弹窗主体
const ModalBody = styled.div`
  padding: ${spacing.lg};
`;

// 表单组
const FormGroup = styled.div`
  margin-bottom: ${spacing.md};
`;

// 标签
const Label = styled.label`
  display: block;
  margin-bottom: ${spacing.xs};
  font-weight: 500;
  color: ${colors.text};
`;

// 输入框
const Input = styled.input`
  width: 100%;
  padding: ${spacing.sm} ${spacing.md};
  border: 1px solid ${colors.border};
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.2s;
  
  &:focus {
    outline: none;
    border-color: ${colors.primary};
    box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.2);
  }
  
  &.error {
    border-color: ${colors.error};
  }
`;

// 错误消息
const ErrorMessage = styled.div`
  color: ${colors.error};
  font-size: 0.875rem;
  margin-top: ${spacing.xs};
  min-height: 1.2rem;
`;

// 提交按钮
const SubmitButton = styled.button`
  width: 100%;
  padding: ${spacing.md};
  background-color: ${colors.primary};
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
  
  &:hover:not(:disabled) {
    background-color: ${colors.primaryDark};
  }
  
  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
`;

// 成功消息
const SuccessMessage = styled.div`
  color: ${colors.success};
  font-size: 0.875rem;
  margin-top: ${spacing.xs};
  text-align: center;
  min-height: 1.2rem;
`;

/**
 * 修改密码弹窗组件
 * @param {boolean} isOpen - 弹窗是否打开
 * @param {Function} onClose - 关闭弹窗的回调函数
 * @param {Function} onSuccess - 修改密码成功的回调函数
 */
function ChangePasswordModal({ isOpen, onClose, onSuccess }) {
  // 表单状态
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  
  // 错误状态
  const [errors, setErrors] = useState({});
  
  // 提交状态
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');
  
  // 验证表单
  const validateForm = () => {
    const newErrors = {};
    
    // 验证当前密码
    if (!currentPassword) {
      newErrors.currentPassword = '请输入当前密码';
    }
    
    // 验证新密码
    if (!newPassword) {
      newErrors.newPassword = '请输入新密码';
    } else if (newPassword.length < 8) {
      newErrors.newPassword = '新密码至少8位';
    } else if (!/\d/.test(newPassword)) {
      newErrors.newPassword = '新密码必须包含数字';
    }
    
    // 验证确认密码
    if (!confirmPassword) {
      newErrors.confirmPassword = '请确认新密码';
    } else if (newPassword !== confirmPassword) {
      newErrors.confirmPassword = '两次输入的密码不一致';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  
  // 处理表单提交
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // 重置状态
    setErrors({});
    setSuccessMessage('');
    
    // 验证表单
    if (!validateForm()) {
      return;
    }
    
    setIsSubmitting(true);
    
    try {
      // 调用API修改密码
      const response = await changePassword({
        currentPassword,
        newPassword
      });
      
      if (response.success) {
        logInfo('密码修改成功');
        setSuccessMessage('密码修改成功');
        
        // 清空表单
        setCurrentPassword('');
        setNewPassword('');
        setConfirmPassword('');
        
        // 调用成功回调
        if (onSuccess) {
          onSuccess();
        }
        
        // 2秒后关闭弹窗
        setTimeout(() => {
          onClose();
        }, 2000);
      } else {
        // 设置错误消息
        setErrors({ general: response.message || '修改密码失败' });
      }
    } catch (error) {
      logError('修改密码失败', { error: error.message });
      setErrors({ general: error.message || '修改密码失败，请稍后再试' });
    } finally {
      setIsSubmitting(false);
    }
  };
  
  // 处理弹窗关闭
  const handleClose = () => {
    // 重置状态
    setErrors({});
    setSuccessMessage('');
    setCurrentPassword('');
    setNewPassword('');
    setConfirmPassword('');
    setIsSubmitting(false);
    
    // 调用关闭回调
    onClose();
  };
  
  // 处理按键事件
  const handleKeyDown = (e) => {
    if (e.key === 'Escape') {
      handleClose();
    }
  };
  
  return (
    <AnimatePresence>
      {isOpen && (
        <ModalOverlay
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          onClick={handleClose}
          onKeyDown={handleKeyDown}
        >
          <ModalContent onClick={(e) => e.stopPropagation()}>
            <ModalHeader>
              <ModalTitle>修改密码</ModalTitle>
              <CloseButton onClick={handleClose}>&times;</CloseButton>
            </ModalHeader>
            
            <ModalBody>
              <form onSubmit={handleSubmit}>
                {/* 当前密码 */}
                <FormGroup>
                  <Label htmlFor="currentPassword">当前密码</Label>
                  <Input
                    id="currentPassword"
                    type="password"
                    value={currentPassword}
                    onChange={(e) => setCurrentPassword(e.target.value)}
                    className={errors.currentPassword ? 'error' : ''}
                    disabled={isSubmitting}
                  />
                  <ErrorMessage>{errors.currentPassword}</ErrorMessage>
                </FormGroup>
                
                {/* 新密码 */}
                <FormGroup>
                  <Label htmlFor="newPassword">新密码</Label>
                  <Input
                    id="newPassword"
                    type="password"
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    className={errors.newPassword ? 'error' : ''}
                    disabled={isSubmitting}
                  />
                  <ErrorMessage>{errors.newPassword}</ErrorMessage>
                </FormGroup>
                
                {/* 确认新密码 */}
                <FormGroup>
                  <Label htmlFor="confirmPassword">确认新密码</Label>
                  <Input
                    id="confirmPassword"
                    type="password"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    className={errors.confirmPassword ? 'error' : ''}
                    disabled={isSubmitting}
                  />
                  <ErrorMessage>{errors.confirmPassword}</ErrorMessage>
                </FormGroup>
                
                {/* 通用错误消息 */}
                <ErrorMessage>{errors.general}</ErrorMessage>
                
                {/* 成功消息 */}
                <SuccessMessage>{successMessage}</SuccessMessage>
                
                {/* 提交按钮 */}
                <SubmitButton type="submit" disabled={isSubmitting}>
                  {isSubmitting ? '修改中...' : '确认修改'}
                </SubmitButton>
              </form>
            </ModalBody>
          </ModalContent>
        </ModalOverlay>
      )}
    </AnimatePresence>
  );
}

export default ChangePasswordModal;